const Controller = require('../core/base_controller')
const assert = require('assert')

class AppController extends Controller {
    /**
     * 实体命名转换 _转驼峰，首字母小写
     * 
     * @param {any} str 
     * @returns 
     * @memberof AppController
     */
    _firstUpperCase(str) {
        const re = /_(\w)/g;
        str = str.replace(re, function ($0, $1) {
            return $1.toUpperCase();
        });
        return str[0].toUpperCase() + str.slice(1);
    }

    /**
     * 获取上下文模型
     * 
     * @param {any} modelName 模型名称
     * @memberof AppController
     */
    _getModel() {
        let modelName = this.ctx.params.modelName
        if (typeof modelName !== 'string') {
            throw new Error('实体名称必须为字符串！');
        }
        modelName = this._firstUpperCase(modelName);
        const model = this.app.model[modelName];
        if (model === undefined) {
            throw new Error('未找到实体对象！');
        }
        return model
    }

    /**
     * 保存
     * 
     * @memberof AppController
     */
    async save() {
        const model = this._getModel()
        let ret = await model.mySave(this.param)
        assert(ret, '保存失败')
        this.success(ret)
    }

    /**
     * 删除
     * 
     * @memberof AppController
     */
    async remove() {
        const param = this.param
        const model = this._getModel()
        const pkName = model.primaryKeyField;
        assert(param[pkName], '未获取到数据键值！')
        let ret = await model.destroy({
            where: {
                [pkName]: param[pkName]
            }
        })
        this.success(ret)
    }

    /**
     * 查询所有数据
     * 
     * @returns 
     * @memberof AppController
     */
    async find() {
        //获取参数
        let param = Object.assign({ raw: true }, this.ctx.query, this.ctx.request.body)
        //获取模型
        const model = this._getModel()
        //获取查询条件
        model.pickWhere(param.where)
        let requestPage = param.limit != null || param.page != null
        let ret = requestPage ? await model.findAll(param) : await model.findAndCountAll(param)
        this.success(ret)
    }

    /**
     * 查询单个记录
     * 
     * @memberof AppController
     */
    async findById() {
        let oid = this.ctx.params.oid
        const model = this._getModel()
        let ret = await model.findById(oid)
        this.success(ret)
    }

}

module.exports = AppController